package com.zkc.blog.uilt;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.commonmark.Extension;
import org.commonmark.ext.gfm.tables.TablesExtension;
import org.commonmark.ext.heading.anchor.HeadingAnchorExtension;
import org.commonmark.node.Link;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.AttributeProvider;
import org.commonmark.renderer.html.AttributeProviderContext;
import org.commonmark.renderer.html.AttributeProviderFactory;
import org.commonmark.renderer.html.HtmlRenderer;

public class MarkdownUnit {

	/**
	*基本方法，markdown转换html
	*/
	public static String markdownToHtml(String content){
	    Parser parser = Parser.builder().build();
	    //Node document = parser.parse("This is *Sparta*");
	    Node document = parser.parse(content);
	    HtmlRenderer renderer = HtmlRenderer.builder().build();
	    return renderer.render(document);  // "<p>This is <em>Sparta</em></p>\n"
	}
	/**
	*扩展，h标题增加id和table转换成html
	*/
	public static String markdownToHtmlEx(String content){
	    //h标题增加id
	    Set<Extension> idEx = Collections.singleton(HeadingAnchorExtension.create());
	    //table转换成html
	    List<Extension> tableEx = Arrays.asList(TablesExtension.create());
	    Parser parser = Parser.builder()
	        .extensions(idEx)
	        .extensions(tableEx)
	        .build();
	    Node document = parser.parse(content);
	    HtmlRenderer renderer = HtmlRenderer.builder()
	        .extensions(idEx)
	        .extensions(tableEx)
	        .attributeProviderFactory(new AttributeProviderFactory() {
				@Override
				public AttributeProvider create(AttributeProviderContext arg0) {
					// TODO Auto-generated method stub
					return new CustomAttributeProvider();
				}
			}
	        )
	        .build();
	    return renderer.render(document); 
	}

	/**
	*处理标签属性
	*/
	static class CustomAttributeProvider implements AttributeProvider{
		@Override
		public void setAttributes(Node node, String tagname, Map<String, String> attr) {
			// TODO Auto-generated method stub
	        //改变a链接的target属性为_blank
	        if(node instanceof Link){
	            attr.put("target","_blank");
	        }
	        //给table加class
/*	        if(node instanceof TableBlock){
	            attr.put("class","ui table");
	        }*/
		}
	}
}
